package com.renli.exception;

import com.renli.result.ResultException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(RenLiException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException customException(RenLiException e) {
        String msg = e.getMsg();
        log.info(msg + "错误的信息");
        return new ResultException(msg);
    }

//    @ExceptionHandler(Exception.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    public ResultException exception(Exception e) {
//        return new ResultException("发生未知错误，请回控制台查看");
//    }
@ExceptionHandler(MethodArgumentNotValidException.class)//捕获系统异常
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码返回500
public ResultException doValidException(MethodArgumentNotValidException argumentNotValidException) {
    //解析异常的信息
    BindingResult bindingResult = argumentNotValidException.getBindingResult();
    List<FieldError> fieldErrors = bindingResult.getFieldErrors();
    List<String> errMsg = new ArrayList<>();
    int size = fieldErrors.size();
    fieldErrors.stream().peek((item) -> {
        errMsg.add(item.getDefaultMessage());
    }).collect(Collectors.toList());
    String join = StringUtils.join(errMsg, ",");
    return new ResultException(join);
}


//    HttpMessageNotReadableException
@ExceptionHandler(HttpMessageNotReadableException.class)//捕获系统异常
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码返回500
public ResultException doHttpMessageNotReadableException(HttpMessageNotReadableException httpMessageNotReadableException) {
    return new ResultException("您将数字输成字符串了！");
}

}
